#include "addgroupdb.h"
#include "pg_common.h"

int main(int argc, char **argv) {
  struct group_t * groupt;
  char sql[512];
  CONNECTION_DB conn = init_db(DB_ARQ_CONF);
  
  PGresult *result;
  int c;
  int force=0;
  
  groupt = (struct group_t *) malloc(sizeof(struct group_t));
  groupt->name=NULL;
  

  if(argc < 2) {
    print_help();
    exit(0);
  }

  while ( (c=getopt (argc, argv, "g:fh")) != -1 ) {
    
    switch (c) {
     
    case 'g':
      groupt->group_id = atoi(optarg);
      break;
        
    case 'h':
      print_help();
      exit(0);
      break;

    case '?':
      break;
      
    }
    
  }
  
  if(optind < argc) {
    groupt->name = strdup(argv[optind++]);
  } else {
    printf("\n     >> Grupo nao especificado << \n\n");
    print_help();
    exit(0);
  }
  
  if( groupt->name == NULL || strlen(groupt->name) < 2 ) {
    printf("\n     >> Nome nao especificado ou com menos de 2 caracteres << \n\n");
    print_help();
    exit(0);
  }

  if(getuid() != 0) {
    printf("Somente o root pode executar esse comando\n");
    exit(0);
  }
  
  //conn = PQconnectdb("host=localhost dbname=users user=postgres");	
  if( conn==NULL) {
    printf("Falha na conexao\n");
    exit(0);
  }
  
  sprintf(sql, "SELECT * FROM group_sys WHERE name='%s'", groupt->name);
  result = PQexec(conn->pgconn, sql);
  if(PQntuples(result)>0) {
    printf("Grupo ja existe\n");
    free_db(conn);
    exit(0);
  }
  
  if (groupt->group_id!=0){
    sprintf(sql, "SELECT * FROM group_sys WHERE group_id='%d'", groupt->group_id);
    result = PQexec(conn->pgconn,sql);
    if (PQntuples(result)>0){
      printf("GID ja usada por outro grupo\n");
      free_db(conn);
      
      exit(0);
    }
  }
  else{
    groupt->group_id = last_group_id(conn);
    if (groupt->group_id==-1){
      printf("Erro\n");
      free_db(conn);
      exit(0);
    }
  }
  
	
  if(force==0) {

    printf("Nome do grupo: %s\n", groupt->name);
    printf("GID do grupo: %d\n", groupt->group_id);

    printf("As informacoes estao corretas? [s/n] ");
    while( (c=getchar()) != 's' && c != 'n' ) {
      printf("As informacoes estao corretas? [s/n] ");
      getchar();
    }
    if(c=='n') exit(0);
    
  }

  sprintf(sql, "INSERT INTO group_sys VALUES (%d, '%s');", groupt->group_id, groupt->name);
  if(PQexec(conn->pgconn, sql)==NULL){
    printf("Erro\n");
  }
  else{
    printf("%s\n", PQerrorMessage(conn->pgconn));
    printf("%d\n", last_group_id(conn->pgconn));
    printf("Grupo adicionado\n");
    if(addgroup(groupt->name, groupt->group_id)!=0)
      printf("Erro ao adicionar no arquivo group\n");
  }
  PQclear(result);
  free_db(conn);
  return 0;

}

void print_help() {

  printf("Uso correto: addgroupdb [options] group\n\n");
  printf("Opcoes:\n");
  printf("  -g		GID para o grupo\n");
  printf("  -h		Mostra essa ajuda\n");
  printf("\nSECURE DB USERS SYSTEM MANAGEMENT\n");

}

int last_group_id(CONNECTION_DB conn) {

  PGresult *result=NULL;
  
  result = PQexec(conn->pgconn,"SELECT group_id FROM group_sys ORDER BY group_id DESC LIMIT 1;");
  if( result != NULL && PQntuples(result) == 1 )
    return (atoi(PQgetvalue(result,0,0))+1);
  else
    return -1;
}

int addgroup(char *name, int group_id) {

   FILE *fp;
   char buffer[1024];

   fp = fopen(GROUPFILE, "a");
   if(fp==NULL) return -1;

   sprintf(buffer, "%s:x:%d:\n", name, group_id);

   fputs(buffer, fp);

   fclose(fp);
   return 0;

}
